/**
 * 成果发表前端脚本
 */

class PublicationCenter {
    constructor() {
        this.baseURL = 'http://localhost:8080';
        this.token = this.getToken();
        this.publications = [];
        this.projects = [];
        this.currentPublication = null;
        this.isEditing = false;
        this.currentFilter = 'all';
        this.stats = null;
        this.currentDocumentUrl = null;
        this.currentDocumentName = null;
    }

    /**
     * 获取JWT令牌
     */
    getToken() {
        return localStorage.getItem('token') || sessionStorage.getItem('token');
    }

    /**
     * 通用API请求方法
     */
    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${this.token}`,
                ...options.headers
            },
            ...options
        };

        try {
            const response = await fetch(url, config);
            
            if (!response.ok) {
                const errorText = await response.text();
                throw new Error(`HTTP ${response.status}: ${errorText}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    /**
     * 获取所有成果
     */
    async loadPublications() {
        try {
            this.showLoading();
            this.publications = await this.request('/publications');
            this.renderPublications();
        } catch (error) {
            this.showError('加载成果列表失败: ' + error.message);
        }
    }

    /**
     * 获取用户成果
     */
    async loadUserPublications() {
        try {
            this.showLoading();
            this.publications = await this.request('/publications/user');
            this.renderPublications();
        } catch (error) {
            this.showError('加载用户成果失败: ' + error.message);
        }
    }

    /**
     * 获取成果统计信息
     */
    async loadStats() {
        try {
            this.stats = await this.request('/publications/stats');
            this.renderStats();
        } catch (error) {
            console.error('加载统计信息失败:', error);
        }
    }

    /**
     * 获取项目列表
     */
    async loadProjects() {
        try {
            this.projects = await this.request('/projects');
            this.renderProjectOptions();
        } catch (error) {
            console.error('加载项目列表失败:', error);
        }
    }

    /**
     * 创建成果
     */
    async createPublication(publicationData) {
        try {
            const newPublication = await this.request('/publications', {
                method: 'POST',
                body: JSON.stringify(publicationData)
            });
            
            this.publications.unshift(newPublication);
            this.renderPublications();
            this.closeModal();
            this.showSuccess('成果创建成功！');
            this.loadStats(); // 刷新统计信息
        } catch (error) {
            this.showModalError('创建成果失败: ' + error.message);
        }
    }

    /**
     * 更新成果
     */
    async updatePublication(id, publicationData) {
        try {
            const updatedPublication = await this.request(`/publications/${id}`, {
                method: 'PUT',
                body: JSON.stringify(publicationData)
            });
            
            const index = this.publications.findIndex(p => p.id === id);
            if (index !== -1) {
                this.publications[index] = updatedPublication;
            }
            
            this.renderPublications();
            this.closeModal();
            this.showSuccess('成果更新成功！');
            this.loadStats(); // 刷新统计信息
        } catch (error) {
            this.showModalError('更新成果失败: ' + error.message);
        }
    }

    /**
     * 删除成果
     */
    async deletePublication(id) {
        if (!confirm('确定要删除这个成果吗？此操作不可撤销。')) {
            return;
        }

        try {
            await this.request(`/publications/${id}`, {
                method: 'DELETE'
            });
            
            this.publications = this.publications.filter(p => p.id !== id);
            this.renderPublications();
            this.showSuccess('成果删除成功！');
            this.loadStats(); // 刷新统计信息
        } catch (error) {
            this.showError('删除成果失败: ' + error.message);
        }
    }

    /**
     * 搜索成果
     */
    async searchPublications() {
        const keyword = document.getElementById('searchInput').value.trim();
        const typeFilter = document.getElementById('typeFilter').value;
        const statusFilter = document.getElementById('statusFilter').value;
        
        try {
            let publications;
            if (keyword) {
                publications = await this.request(`/publications/search?keyword=${encodeURIComponent(keyword)}`);
            } else {
                publications = await this.request('/publications');
            }
            
            // 应用筛选条件
            if (typeFilter) {
                publications = publications.filter(pub => pub.type === typeFilter);
            }
            if (statusFilter) {
                publications = publications.filter(pub => pub.status === statusFilter);
            }
            
            this.publications = publications;
            this.renderPublications();
        } catch (error) {
            this.showError('搜索成果失败: ' + error.message);
        }
    }

    /**
     * 筛选成果
     */
    async filterPublications(filterType) {
        this.currentFilter = filterType;
        
        // 更新筛选标签样式
        document.querySelectorAll('.filter-tab').forEach(tab => {
            tab.classList.remove('active');
        });
        event.target.classList.add('active');
        
        try {
            let publications;
            switch (filterType) {
                case 'all':
                    publications = await this.request('/publications');
                    break;
                case 'my':
                    publications = await this.request('/publications/user');
                    break;
                case 'published':
                    publications = await this.request('/publications');
                    publications = publications.filter(pub => pub.status === 'PUBLISHED');
                    break;
                case 'thisyear':
                    publications = await this.request('/publications');
                    const currentYear = new Date().getFullYear();
                    publications = publications.filter(pub => 
                        pub.publishDate && new Date(pub.publishDate).getFullYear() === currentYear
                    );
                    break;
                default:
                    publications = await this.request('/publications');
            }
            
            this.publications = publications;
            this.renderPublications();
        } catch (error) {
            this.showError('筛选成果失败: ' + error.message);
        }
    }

    /**
     * 渲染统计信息
     */
    renderStats() {
        if (!this.stats) return;
        
        const container = document.getElementById('statsContainer');
        container.innerHTML = `
            <div class="stat-card">
                <div class="stat-number">${this.stats.totalCount || 0}</div>
                <div class="stat-label">总成果数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${this.stats.publishedCount || 0}</div>
                <div class="stat-label">已发表</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${this.stats.thisYearCount || 0}</div>
                <div class="stat-label">今年发表</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${this.stats.journalCount || 0}</div>
                <div class="stat-label">期刊论文</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${this.stats.conferenceCount || 0}</div>
                <div class="stat-label">会议论文</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${this.stats.totalCitations || 0}</div>
                <div class="stat-label">总引用数</div>
            </div>
            <div class="stat-card">
                <div class="stat-number">${this.stats.averageImpactFactor ? this.stats.averageImpactFactor.toFixed(3) : '0.000'}</div>
                <div class="stat-label">平均影响因子</div>
            </div>
        `;
    }

    /**
     * 渲染成果列表
     */
    renderPublications() {
        const container = document.getElementById('publicationsContainer');
        
        if (this.publications.length === 0) {
            container.innerHTML = `
                <div class="empty-state">
                    <h3>暂无成果</h3>
                    <p>点击"新建成果"按钮创建第一个成果</p>
                </div>
            `;
            return;
        }

        const publicationsHTML = this.publications.map(pub => this.renderPublicationCard(pub)).join('');
        container.innerHTML = `<div class="publications-grid">${publicationsHTML}</div>`;
    }

    /**
     * 渲染单个成果卡片
     */
    renderPublicationCard(publication) {
        const typeClass = this.getTypeClass(publication.type);
        const statusClass = this.getStatusClass(publication.status);
        
        return `
            <div class="publication-card">
                <div class="publication-header">
                    <h3 class="publication-title">${publication.title || '未命名成果'}</h3>
                    <span class="publication-type ${typeClass}">
                        ${this.getTypeText(publication.type)}
                    </span>
                </div>
                
                <div class="publication-meta">
                    <div class="publication-meta-item">
                        <span>👤</span>
                        <span>${publication.authors || '未知作者'}</span>
                    </div>
                    ${publication.journal ? `
                        <div class="publication-meta-item">
                            <span>📖</span>
                            <span>${publication.journal}</span>
                        </div>
                    ` : ''}
                    ${publication.publishDate ? `
                        <div class="publication-meta-item">
                            <span>📅</span>
                            <span>${publication.publishDate}</span>
                        </div>
                    ` : ''}
                    ${publication.projectName ? `
                        <div class="publication-meta-item">
                            <span>📁</span>
                            <span>${publication.projectName}</span>
                        </div>
                    ` : ''}
                    ${publication.impactFactor ? `
                        <div class="publication-meta-item">
                            <span>📊</span>
                            <span>影响因子: ${publication.impactFactor}</span>
                        </div>
                    ` : ''}
                    ${publication.citationCount ? `
                        <div class="publication-meta-item">
                            <span>📈</span>
                            <span>引用: ${publication.citationCount}</span>
                        </div>
                    ` : ''}
                </div>
                
                ${publication.abstractText ? `<div class="publication-abstract">${publication.abstractText}</div>` : ''}
                
                <div class="publication-status ${statusClass}">
                    ${this.getStatusText(publication.status)}
                </div>
                
                <div class="publication-actions">
                    <button class="btn btn-primary btn-sm" onclick="publicationCenter.viewPublication(${publication.id})">
                        👁️ 查看
                    </button>
                    <button class="btn btn-warning btn-sm" onclick="publicationCenter.editPublication(${publication.id})">
                        ✏️ 编辑
                    </button>
                    ${publication.doi ? `
                        <button class="btn btn-primary btn-sm" onclick="window.open('https://doi.org/${publication.doi}', '_blank')">
                            🔗 DOI
                        </button>
                    ` : ''}
                    ${publication.url ? `
                        <button class="btn btn-primary btn-sm" onclick="window.open('${publication.url}', '_blank')">
                            🌐 链接
                        </button>
                    ` : ''}
                    ${publication.documentUrl ? `
                        <button class="btn btn-primary btn-sm" onclick="publicationCenter.previewDocument('${publication.documentUrl}', '${publication.documentName}')">
                            📄 文档
                        </button>
                    ` : ''}
                    <button class="btn btn-danger btn-sm" onclick="publicationCenter.deletePublication(${publication.id})">
                        🗑️ 删除
                    </button>
                </div>
            </div>
        `;
    }

    /**
     * 渲染项目选项
     */
    renderProjectOptions() {
        const select = document.getElementById('projectId');
        select.innerHTML = '<option value="">请选择项目</option>' +
            this.projects.map(project => `
                <option value="${project.id}">${project.projectName}</option>
            `).join('');
    }

    /**
     * 获取类型样式类
     */
    getTypeClass(type) {
        const typeMap = {
            'JOURNAL': 'type-journal',
            'CONFERENCE': 'type-conference',
            'PATENT': 'type-patent',
            'SOFTWARE': 'type-software',
            'BOOK': 'type-book',
            'OTHER': 'type-other'
        };
        return typeMap[type] || 'type-other';
    }

    /**
     * 获取类型显示文本
     */
    getTypeText(type) {
        const typeMap = {
            'JOURNAL': '期刊论文',
            'CONFERENCE': '会议论文',
            'PATENT': '专利',
            'SOFTWARE': '软件著作权',
            'BOOK': '专著',
            'OTHER': '其他'
        };
        return typeMap[type] || type;
    }

    /**
     * 获取状态样式类
     */
    getStatusClass(status) {
        const statusMap = {
            'DRAFT': 'status-draft',
            'SUBMITTED': 'status-submitted',
            'UNDER_REVIEW': 'status-under-review',
            'ACCEPTED': 'status-accepted',
            'PUBLISHED': 'status-published',
            'REJECTED': 'status-rejected'
        };
        return statusMap[status] || 'status-draft';
    }

    /**
     * 获取状态显示文本
     */
    getStatusText(status) {
        const statusMap = {
            'DRAFT': '草稿',
            'SUBMITTED': '投稿中',
            'UNDER_REVIEW': '审稿中',
            'ACCEPTED': '已接收',
            'PUBLISHED': '已发表',
            'REJECTED': '被拒绝'
        };
        return statusMap[status] || status;
    }

    /**
     * 显示创建成果模态框
     */
    showCreateModal() {
        this.isEditing = false;
        this.currentPublication = null;

        document.getElementById('modalTitle').textContent = '新建成果';
        document.getElementById('publicationForm').reset();
        document.getElementById('modalError').style.display = 'none';

        // 加载项目列表
        this.loadProjects();

        document.getElementById('publicationModal').style.display = 'block';
    }

    /**
     * 查看成果详情
     */
    async viewPublication(id) {
        try {
            const publication = await this.request(`/publications/${id}`);
            this.showPublicationDetails(publication, true); // 只读模式
        } catch (error) {
            this.showError('获取成果详情失败: ' + error.message);
        }
    }

    /**
     * 编辑成果
     */
    async editPublication(id) {
        try {
            const publication = await this.request(`/publications/${id}`);
            this.showPublicationDetails(publication, false); // 编辑模式
        } catch (error) {
            this.showError('获取成果详情失败: ' + error.message);
        }
    }

    /**
     * 显示成果详情
     */
    showPublicationDetails(publication, readOnly = false) {
        this.isEditing = !readOnly;
        this.currentPublication = publication;

        document.getElementById('modalTitle').textContent = readOnly ? '成果详情' : '编辑成果';
        document.getElementById('modalError').style.display = 'none';

        // 填充表单数据
        document.getElementById('title').value = publication.title || '';
        document.getElementById('type').value = publication.type || 'JOURNAL';
        document.getElementById('status').value = publication.status || 'DRAFT';
        document.getElementById('authors').value = publication.authors || '';
        document.getElementById('journal').value = publication.journal || '';
        document.getElementById('abstractText').value = publication.abstractText || '';
        document.getElementById('keywords').value = publication.keywords || '';
        document.getElementById('publishDate').value = publication.publishDate || '';
        document.getElementById('doi').value = publication.doi || '';
        document.getElementById('url').value = publication.url || '';
        document.getElementById('impactFactor').value = publication.impactFactor || '';
        document.getElementById('citationCount').value = publication.citationCount || '';

        // 设置文档信息
        this.currentDocumentUrl = publication.documentUrl;
        this.currentDocumentName = publication.documentName;
        this.updateDocumentDisplay();

        // 加载项目列表并设置当前值
        this.loadProjects().then(() => {
            document.getElementById('projectId').value = publication.projectId || '';
        });

        // 设置表单只读状态
        const formElements = document.querySelectorAll('#publicationForm input, #publicationForm select, #publicationForm textarea');
        formElements.forEach(element => {
            element.disabled = readOnly;
        });

        // 更新保存按钮
        const saveButton = document.querySelector('.modal-footer .btn-success');
        if (readOnly) {
            saveButton.style.display = 'none';
        } else {
            saveButton.style.display = 'inline-block';
            saveButton.textContent = '更新';
        }

        document.getElementById('publicationModal').style.display = 'block';
    }

    /**
     * 上传文档
     */
    async uploadDocument(file) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('category', 'publication');

        try {
            const response = await fetch(`${this.baseURL}/files/upload`, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${this.token}`
                },
                body: formData
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            const result = await response.json();
            if (result.success) {
                this.currentDocumentUrl = result.fileUrl;
                this.currentDocumentName = result.fileName;
                this.updateDocumentDisplay();
                return result;
            } else {
                throw new Error(result.message);
            }
        } catch (error) {
            console.error('文档上传失败:', error);
            throw error;
        }
    }

    /**
     * 更新文档显示
     */
    updateDocumentDisplay() {
        const currentDocDiv = document.getElementById('currentDocument');
        const fileNameSpan = document.getElementById('currentFileName');

        if (this.currentDocumentUrl && this.currentDocumentName) {
            fileNameSpan.textContent = this.currentDocumentName;
            currentDocDiv.style.display = 'block';
        } else {
            currentDocDiv.style.display = 'none';
        }
    }

    /**
     * 预览文档
     */
    previewDocument(documentUrl = null, documentName = null) {
        const url = documentUrl || this.currentDocumentUrl;
        const name = documentName || this.currentDocumentName;

        if (!url) {
            alert('没有可预览的文档');
            return;
        }

        // 创建预览模态框
        const previewModal = document.createElement('div');
        previewModal.className = 'modal';
        previewModal.style.display = 'block';
        previewModal.innerHTML = `
            <div class="modal-content" style="max-width: 90%; max-height: 90%;">
                <div class="modal-header">
                    <h3>📄 文档预览 - ${name}</h3>
                    <span class="close" onclick="this.closest('.modal').remove()">&times;</span>
                </div>
                <div class="modal-body" style="padding: 0;">
                    <div class="document-preview">
                        <div class="file-info">
                            文件名: ${name} |
                            <a href="${this.baseURL}${url.replace('/preview/', '/download/')}" target="_blank">📥 下载</a>
                        </div>
                        <iframe src="${this.baseURL}${url}" style="height: 600px;"></iframe>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(previewModal);

        // 点击外部关闭
        previewModal.addEventListener('click', (e) => {
            if (e.target === previewModal) {
                previewModal.remove();
            }
        });
    }

    /**
     * 删除文档
     */
    async removeDocument() {
        if (!this.currentDocumentUrl) {
            return;
        }

        if (!confirm('确定要删除当前文档吗？')) {
            return;
        }

        try {
            // 从URL中提取文件名
            const fileName = this.currentDocumentUrl.split('/').pop();

            await fetch(`${this.baseURL}/files/publication/${fileName}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${this.token}`
                }
            });

            this.currentDocumentUrl = null;
            this.currentDocumentName = null;
            this.updateDocumentDisplay();
            this.showSuccess('文档删除成功');
        } catch (error) {
            console.error('删除文档失败:', error);
            this.showError('删除文档失败: ' + error.message);
        }
    }

    /**
     * 保存成果
     */
    async savePublication() {
        const form = document.getElementById('publicationForm');
        const formData = new FormData(form);

        const publicationData = {
            title: formData.get('title'),
            type: formData.get('type'),
            status: formData.get('status'),
            authors: formData.get('authors'),
            journal: formData.get('journal'),
            abstractText: formData.get('abstractText'),
            keywords: formData.get('keywords'),
            publishDate: formData.get('publishDate') || null,
            doi: formData.get('doi'),
            url: formData.get('url'),
            impactFactor: formData.get('impactFactor') ? parseFloat(formData.get('impactFactor')) : null,
            citationCount: formData.get('citationCount') ? parseInt(formData.get('citationCount')) : null,
            projectId: formData.get('projectId') ? parseInt(formData.get('projectId')) : null,
            documentUrl: this.currentDocumentUrl,
            documentName: this.currentDocumentName
        };

        // 验证必填字段
        if (!publicationData.title || !publicationData.type || !publicationData.status || !publicationData.authors) {
            this.showModalError('请填写所有必填字段');
            return;
        }

        if (this.isEditing && this.currentPublication) {
            await this.updatePublication(this.currentPublication.id, publicationData);
        } else {
            await this.createPublication(publicationData);
        }
    }

    /**
     * 关闭模态框
     */
    closeModal() {
        document.getElementById('publicationModal').style.display = 'none';
        document.getElementById('publicationForm').reset();
        document.getElementById('modalError').style.display = 'none';

        // 恢复表单可编辑状态
        const formElements = document.querySelectorAll('#publicationForm input, #publicationForm select, #publicationForm textarea');
        formElements.forEach(element => {
            element.disabled = false;
        });

        // 恢复保存按钮
        const saveButton = document.querySelector('.modal-footer .btn-success');
        saveButton.style.display = 'inline-block';
        saveButton.textContent = '保存';
    }

    /**
     * 显示加载状态
     */
    showLoading() {
        const container = document.getElementById('publicationsContainer');
        container.innerHTML = '<div class="loading">加载中...</div>';
    }

    /**
     * 显示错误信息
     */
    showError(message) {
        const container = document.getElementById('publicationsContainer');
        container.innerHTML = `<div class="error">❌ ${message}</div>`;
    }

    /**
     * 显示模态框错误信息
     */
    showModalError(message) {
        const errorDiv = document.getElementById('modalError');
        errorDiv.textContent = message;
        errorDiv.style.display = 'block';
    }

    /**
     * 显示成功信息
     */
    showSuccess(message) {
        // 创建临时成功提示
        const successDiv = document.createElement('div');
        successDiv.className = 'success';
        successDiv.textContent = '✅ ' + message;
        successDiv.style.position = 'fixed';
        successDiv.style.top = '20px';
        successDiv.style.right = '20px';
        successDiv.style.zIndex = '9999';
        successDiv.style.padding = '15px 20px';
        successDiv.style.borderRadius = '4px';
        successDiv.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';

        document.body.appendChild(successDiv);

        setTimeout(() => {
            document.body.removeChild(successDiv);
        }, 3000);
    }

    /**
     * 初始化
     */
    init() {
        // 检查登录状态
        if (!this.token) {
            alert('请先登录');
            window.location.href = '/login.html';
            return;
        }

        // 加载统计信息和成果列表
        this.loadStats();
        this.loadPublications();

        // 绑定搜索框回车事件
        document.getElementById('searchInput').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.searchPublications();
            }
        });

        // 绑定模态框点击外部关闭事件
        document.getElementById('publicationModal').addEventListener('click', (e) => {
            if (e.target === document.getElementById('publicationModal')) {
                this.closeModal();
            }
        });

        // 绑定文件上传事件
        document.getElementById('documentFile').addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (file) {
                const progressDiv = document.getElementById('uploadProgress');
                const progressFill = progressDiv.querySelector('.progress-fill');
                const progressText = progressDiv.querySelector('.progress-text');

                try {
                    progressDiv.style.display = 'block';
                    progressText.textContent = '上传中...';

                    // 模拟上传进度
                    let progress = 0;
                    const progressInterval = setInterval(() => {
                        progress += 10;
                        progressFill.style.width = progress + '%';
                        if (progress >= 90) {
                            clearInterval(progressInterval);
                        }
                    }, 100);

                    await this.uploadDocument(file);

                    clearInterval(progressInterval);
                    progressFill.style.width = '100%';
                    progressText.textContent = '上传完成';

                    setTimeout(() => {
                        progressDiv.style.display = 'none';
                        progressFill.style.width = '0%';
                    }, 1000);

                    this.showSuccess('文档上传成功');
                } catch (error) {
                    progressDiv.style.display = 'none';
                    progressFill.style.width = '0%';
                    this.showModalError('文档上传失败: ' + error.message);
                }

                // 清空文件输入
                e.target.value = '';
            }
        });
    }
}

// 全局函数
function showCreateModal() {
    publicationCenter.showCreateModal();
}

function closeModal() {
    publicationCenter.closeModal();
}

function savePublication() {
    publicationCenter.savePublication();
}

function loadPublications() {
    publicationCenter.loadPublications();
}

function searchPublications() {
    publicationCenter.searchPublications();
}

function filterPublications(filterType) {
    publicationCenter.filterPublications(filterType);
}

function previewDocument() {
    publicationCenter.previewDocument();
}

function removeDocument() {
    publicationCenter.removeDocument();
}

// 创建全局实例
const publicationCenter = new PublicationCenter();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    publicationCenter.init();
});
